<template>
	<view class="test-alova-list-page">
		<wd-cell v-for="(item, index) in list" :key="index" :title="item.title" is-link />
		<wd-loadmore custom-class="loadmore" :state="loadmoreState" />
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted } from 'vue';
	import { useRequest } from 'alova/client';
	import { getDemoList } from '@/common/api/api';
	import { onReachBottom } from '@dcloudio/uni-app'

	const pageNo = ref(1);
	const pageSize = 20;
	const total = ref(0);
	const list = ref<any[]>([]);
	const finished = ref(false);

	const { data, send, loading } = useRequest(
		() => getDemoList({ pageNo: pageNo.value, pageSize }),
		{ immediate: false },//禁止字段触发
	);
	
	// 计算属性优化 loadmore 状态
	const loadmoreState = computed(() => {
		if (finished.value) return 'finished';
		if (loading.value) return 'loading';
		return 'loadmore';
	});

	const handleResponse = () => {
		if (!data.value) return;

		const newList = data.value.data?.list || [];
		total.value = data.value.data?.total || 0;

		list.value.push(...newList);
		finished.value = list.value.length >= total.value;
	};

	const init = async () => {
		pageNo.value = 1;
		list.value = [];
		finished.value = false;
		await send();
		handleResponse();
		pageNo.value++;
	};

	//滚动到底部
	onReachBottom(async () => {
		if (finished.value || loading.value) return;
		await send();
		handleResponse();
		pageNo.value++;
	});

	//加载完成
	onMounted(() => {
		init();
	});

	
</script>

<style scoped>
	.test-alova-list-page {
		padding: 20rpx;
	}
</style>